import PoolManage from "../Manages/poolManage";
let PoolConfig = {
  greenBullet: "bulletPool",
  blueBullet: "bullet1Pool",
  enemyBullet: "enemyBulletPool",
  enemy1: "enemy1Pool",
  enemy2: "enemy2Pool",
  enemy3: "enemy3Pool",
  yellowBullet: "bossBullet1",
  jigaungBullet: "bossBullet2",
  daodan: "bossBullet3",
}

cc.Class({
  extends: cc.Component,

  properties: {
    Bg_bg: cc.Node,
    Bg_bg2: cc.Node,
    playerNode: cc.Node,
    laster: cc.Node,
    bulletPrefab: cc.Prefab,
    gengzong_bulletPre: cc.Prefab,
    bulletPrefab1: cc.Prefab,
    enemyBullet: cc.Prefab,
    PauseBg: cc.Node,
    isOverBg: cc.Node,
    isWinBg: cc.Node,
    enemyPrefab1: cc.Prefab,
    enemyPrefab2: cc.Prefab,
    enemyPrefab3: cc.Prefab,
    enemyBoss: cc.Prefab,
    yellowBullet: cc.Prefab,
    jigaungBullet: cc.Prefab,
    daodan: cc.Prefab,
    bloodBag: cc.Prefab,
    AX: cc.Node,
    AX2: cc.Node,
    AX3: cc.Node,
    ScoreLable: cc.Label,
    MaxScoreLable: cc.Label,
    levelView: cc.Label,
    killEnemy_bar: cc.Node,
    hitWarning: cc.Node,
    BossWarning: cc.Node,

    audio: {
      //bgm
      default: null,
      type: cc.AudioClip,
    },
    button_sound: {
      //点击音效
      type: cc.AudioClip,
      default: null,
    },
    button_sound1: {
      //爆炸音效
      type: cc.AudioClip,
      default: null,
    },
    Im_sound: cc.Node,
    Im_nosound: cc.Node,
    trackButton: cc.Node,
    enemyBossMoveTime: 2,
  },

  onLoad() {
    window.game = this;
    this.viewWidth = cc.view.getVisibleSize().width;
    this.viewHeight = cc.view.getVisibleSize().height;
    cc.director.getCollisionManager().enabled = true; //开启碰撞
    this.current = cc.audioEngine.play(this.audio, true, 1);

    this.Bg_bg.y = 0;
    this.Bg_bg2.y = this.Bg_bg.y + this.Bg_bg.height;

    PoolManage.objectPools = {};
    this.pools = PoolManage.getInstance();
    this.initPool();//初始化对象池

    this.ft = 0;
    this.creatEnemytime = 0;
    this.isStart = true;
    this.isCreatBoss = false;
    // this.creatBoss()

    this.PauseBg.zIndex = 2;
    this.isOverBg.zIndex = 2;
    this.playerNode.y = -417;
    this.randomNum = [60, 90, 100];
    this.playerAX = [this.AX, this.AX2, this.AX3];//玩家血量显示
    this.gameTime = 0;
    this.initGameModel();
    this.setTouch();
    this.initHaveBullet(DataMangrt.level);
    this.initBg();

    console.log('初始化完成');
  },

  initBg() {
    let viewSize = cc.view.getCanvasSize()
    this.Bg_bg.height = viewSize.height;
    this.Bg_bg2.height = viewSize.height;
    this.Bg_bg.y = 0;
    this.Bg_bg2.y = this.Bg_bg.y + this.Bg_bg.height;
    console.log('初始化完成', viewSize);
  },
  initGameModel: function () {
    //加载模式
    if (DataMangrt.level) {
      //关卡模式
      if (DataMangrt.level > 10) {
        DataMangrt.level = 10;
      }
      this.ScoreLable.string = " "; //关卡模式隐藏积分
      this.MaxScoreLable.string = " ";
      this.levelView._string = "level " + DataMangrt.level; //初始化关卡显示
    } else {
      //无尽模式
      this.killEnemy_bar.active = false; //隐藏进度条
      this.levelView._string = ""; //隐藏关卡
      this.ScoreLable.zIndex = 3;
      this.MaxScoreLable.zIndex = 3;
      this.scoreNum = 0;
      this.MaxscoreNum = cc.sys.localStorage.getItem("MaxScore");
      if (this.MaxscoreNum == null) {
        this.MaxscoreNum = 0;
      }
      this.addScore(0); //积分初始化
    }
  },
  initPool: function () {
    this.pools.createObjectPool(PoolConfig.greenBullet, this.bulletPrefab, 20);
    this.pools.createObjectPool(PoolConfig.blueBullet, this.bulletPrefab1, 20);
    this.pools.createObjectPool(PoolConfig.enemy1, this.enemyPrefab1, 5);
    this.pools.createObjectPool(PoolConfig.enemy2, this.enemyPrefab2, 5);
    this.pools.createObjectPool(PoolConfig.enemy3, this.enemyPrefab3, 5);
    this.pools.createObjectPool(PoolConfig.enemyBullet, this.enemyBullet, 20);
    this.pools.createObjectPool(PoolConfig.yellowBullet, this.yellowBullet, 20);
    this.pools.createObjectPool(PoolConfig.jigaungBullet, this.jigaungBullet, 20);
    this.pools.createObjectPool(PoolConfig.daodan, this.daodan, 10);
  },
  setTouch: function () {
    this.node.on(
      "touchmove",
      function (event) {
        //飞机移动
        if (DataMangrt.Game_isWin || this.isStart == false) return;
        var pos_player = this.playerNode.getPosition();
        var pos_move = event.getDelta();
        var end_pos = cc.v2(
          pos_player.x + pos_move.x,
          pos_player.y + pos_move.y
        );
        if (end_pos.x < -this.viewWidth / 2) {
          //屏幕检测
          end_pos.x = -this.viewWidth / 2;
        } else if (end_pos.x > this.viewWidth / 2) {
          end_pos.x = this.viewWidth / 2;
        }
        if (end_pos.y < -this.viewHeight / 2) {
          end_pos.y = -this.viewHeight / 2;
        } else if (end_pos.y > this.viewHeight / 2) {
          end_pos.y = this.viewHeight / 2;
        }
        this.playerNode.setPosition(end_pos);
      },
      this
    );
  },
  onclickBt: function (target, data) {
    if (data == "ispause") {
      //点击暂停
      this.PauseBg.active = true;
      this.isStart = false;
    } else if (data == "offPause") {
      //恢复游戏
      this.onclickSound();
      this.PauseBg.active = false;
      this.isStart = true;
    } else if (data == "Isagain") {
      //重新开始
      this.onclickSound();
      DataMangrt.initData();
      cc.director.loadScene("game");
    } else if (data == "Bighome") {
      cc.director.loadScene("start");
      this.onclickSound();
    } else if (data == "AgainTZ") {
      //isOverBg 重新挑战
      this.onclickSound();
      DataMangrt.initData();
      cc.director.loadScene("game");
    } else if (data == "BackHome") {
      //返回大厅
      cc.director.loadScene("start");
      this.onclickSound();
    } else if (data == "sound") {
      this.Im_sound.active = false;
      this.Im_nosound.active = true;
      this.onDestroy();
    } else if (data == "nosound") {
      this.onResume();
    } else if (data == "nextLevel") {
      //下一关按钮
      this.onNextLevelClick();
    } else if (data == "genzong") {
      //跟踪子弹按钮
      this.onTrackBulletClick();
      this.showCountDown();
    } else if (data == "laster1") {
      this.isLasterAttack = true;
      this.laster.active = true;
      console.log("发射激光");
      this.laster.height = 1000;
      this.scheduleOnce(() => {
        this.isLasterAttack = false;
        this.laster.active = false;
      }, 10);
    }
  },
  initHaveBullet: function (level) {
    if (level) {
      if (level <= 7 && level >= 5) {
        //解锁跟踪子弹
        this.trackButton.active = true;
      } else {
        //解锁激光
        this.trackButton.active = true;
      }
    }
    else {
      this.trackButton.active = true;
    }
  },
  onNextLevelClick: function () {
    DataMangrt.initData();
    if (DataMangrt.level < DataMangrt.NowMaxLevel - 1) {
      DataMangrt.level++;
    } else {
      DataMangrt.level = DataMangrt.NowMaxLevel;
    }
    console.log("进入关卡", DataMangrt.level);
    this.initHaveBullet();
    cc.director.loadScene("game");
  },
  onTrackBulletClick: function () {
    DataMangrt.bullet_model = "genzong_bullet";
    this.TrackBulletNum = 10;
    this.enemyArrayPush();
    console.log("跟踪子弹");
    this.shootGengZongBullet();
  },
  onDestroy: function () {
    //暂停bgm
    cc.audioEngine.pause(this.current);
  },
  onResume: function () {
    //恢复bgm
    cc.audioEngine.resume(this.current);
    this.Im_nosound.active = false;
    this.Im_sound.active = true;
  },
  onclickSound: function (event, data) {
    //点击音效
    cc.audioEngine.play(this.button_sound, false, 1);
  },
  addScore: function (score) {
    if (DataMangrt.level) {
      return;
    }
    this.scoreNum = this.scoreNum + score;
    this.ScoreLable.string = "积分:" + this.scoreNum;
    if (this.MaxscoreNum < this.scoreNum) {
      this.MaxscoreNum = this.scoreNum;
      cc.sys.localStorage.setItem("MaxScore", this.MaxscoreNum);
    }
    this.MaxScoreLable.string = "历史最高:" + this.MaxscoreNum;
  },
  showCountDown() {
    let trackBtn = this.trackButton.getComponent(cc.Button);
    trackBtn.interactable = false; //禁止按钮交互
    let CountdownBg = this.trackButton.getChildByName("CountdownBg");
    CountdownBg.active = true; //显示倒计时
    trackBtn.schedule(
      () => {
        let fillRange = CountdownBg.getComponent(cc.Sprite).fillRange;
        fillRange -= 0.01;
        if (fillRange <= 0) {
          trackBtn.interactable = true;
          CountdownBg.active = false;
          fillRange = 1;
        }
        CountdownBg.getComponent(cc.Sprite).fillRange = fillRange;
      },
      0.1,
      99
    );
  },
  Bg_Moving: function () {
    this.Bg_bg.y -= 4;
    this.Bg_bg2.y -= 4;
    // if (this.Bg_bg.y <= -this.Bg_bg.height) {
    //   this.Bg_bg.y = this.Bg_bg2.y + this.Bg_bg.height;
    // }
    // if (this.Bg_bg2.y <= -this.Bg_bg.height) {
    //   this.Bg_bg2.y = this.Bg_bg.y + this.Bg_bg.height;
    // }
    if (this.Bg_bg.y <= -this.Bg_bg.height) {
      this.Bg_bg.y = this.Bg_bg2.y + this.Bg_bg2.height; // 重置位置
    }
    if (this.Bg_bg2.y <= -this.Bg_bg2.height) {
      this.Bg_bg2.y = this.Bg_bg.y + this.Bg_bg.height; // 重置位置
    }
  },
  Creat_Bullet: function (x, y, bulletPool, bulletPrefab) {
    //创建子弹
    if (DataMangrt.Game_isWin) return;
    let bullet = null;
    bullet = this.pools.getNode(bulletPool, bulletPrefab);
    if (bullet) {
      bullet.parent = this.node;
      bullet.setPosition(x, y);
      cc.audioEngine.play(this.button_sound1, false, 1);
    }
  },

  Creat_gengZongBullet: function (x, y) {
    //创建跟踪子弹
    let bullet = null;
    bullet = cc.instantiate(this.gengzong_bulletPre);
    bullet.parent = this.node;
    bullet.setPosition(x, y);
  },
  shootGengZongBullet: function () {
    //发射跟踪子弹
    var enemyNum = DataMangrt.enemyArray.length;
    var pos = this.playerNode.getPosition();
    var array = [];
    if (enemyNum) {
      this.Creat_gengZongBullet(pos.x, pos.y);
      for (var i = 1; i <= enemyNum; i++) {
        array.push(i * 30);
        array.push(-i * 30);
      }
      for (let j = 0; j < array.length; j++) {
        this.Creat_gengZongBullet(pos.x + array[j], pos.y);
      }
    }
  },
  shoot() {
    //发射普通子弹
    if (DataMangrt.Game_isWin) return;
    var pos = this.playerNode.getPosition();
    let j = [-40, 40];
    this.Creat_Bullet(pos.x, pos.y, PoolConfig.greenBullet, this.bulletPrefab);//单列绿色子弹
    if (DataMangrt.level > 7 || DataMangrt.level == 0) {
      for (let i = 0; i < 2; i++) {
        this.Creat_Bullet(pos.x + 2 * j[i], pos.y - 20, PoolConfig.blueBullet, this.bulletPrefab1);//蓝色子弹
        this.Creat_Bullet(pos.x + j[i], pos.y, PoolConfig.greenBullet, this.bulletPrefab);//两列绿色子弹
      }
    }
    else if (DataMangrt.level > 3) {
      for (let i = 0; i < 2; i++) {
        this.Creat_Bullet(pos.x + j[i], pos.y, PoolConfig.greenBullet, this.bulletPrefab);//两列绿色子弹
      }
    }

  },
  creatProps: function () {
    //创建道具
    let e = this;
    let props = cc.v2(0, e.viewHeight);
    e.blood = cc.instantiate(e.bloodBag); //血包
    e.blood.parent = cc.find("Canvas/NULL_Node");
    props.x = -e.viewWidth / 2 + Math.random() * e.viewWidth; //随机位置
    e.blood.setPosition(props);

    // 设置目标位置的世界坐标
    // var targetWorldPos3 = cc.v2(e.blood.width/2, e.viewHeight/4);
    var targetWorldPos2 = cc.v2(
      e.viewWidth - e.blood.width / 2,
      e.viewHeight / 2
    );
    var targetWorldPos4 = cc.v2(0, 0);

    // 将目标位置从世界坐标转换为节点的局部坐标
    var targetLocalPos2 = e.blood.parent.convertToNodeSpaceAR(targetWorldPos2);
    var targetLocalPos4 = e.blood.parent.convertToNodeSpaceAR(targetWorldPos4);

    cc.tween(e.blood)
      .to(2, { position: targetLocalPos2 })
      .to(2, { position: targetLocalPos4 })
      .call(() => {
        e.blood.destroy();
        console.log("销毁血包");
      })
      .start();
  },
  creatEnemyPos: function (poolName, enemyPrefab, enemyType) {
    if (!this.isStart || DataMangrt.Game_isWin) return;
    let enemy = null;
    let e = this;
    let pos_enemy = cc.v2(0, 0);
    enemy = this.pools.getNode(poolName, enemyPrefab)
    pos_enemy.x = -e.viewWidth / 2 + Math.random() * e.viewWidth; //随机位置
    enemy.parent = e.node;
    let enemyJs = enemy.getComponent("enemy" + enemyType);
    if (enemyJs) {
      enemyJs.init();
    }
    enemy.setPosition(pos_enemy.x, 666);
    return cc.v2(pos_enemy.x, 666);
  },

  enemyArrayPush: function () {
    //将敌人添加到敌人数组
    var allNodeArray = this.node.children;
    var enemyArray = DataMangrt.enemyArray;
    var newarr = [];
    for (let i = 0; i < allNodeArray.length; i++) {
      let enemyStr = allNodeArray[i]._name.slice(0, 11);
      if (enemyStr == "enemyprefab") {
        if (enemyArray.length == 0) {
          enemyArray.push(allNodeArray[i]);
        } else {
          newarr.push(allNodeArray[i]);
        }
      }
    }
    DataMangrt.enemyArray = newarr;
  },
  Creat_Enemy: function (enemyType) {
    if (this.isCreatBoss) return;
    if (enemyType == 1) {
      //创建敌人1
      this.creatEnemyPos(PoolConfig.enemy1, this.enemyPrefab1, "");
    } else if (enemyType == 2) {
      //创建敌人2
      this.creatEnemyPos(PoolConfig.enemy2, this.enemyPrefab2, "2");
    } else if (enemyType == 3) {
      //创建敌人3
      let enemy3_pos = this.creatEnemyPos(PoolConfig.enemy3, this.enemyPrefab3, "3");
      this.createEnemyBullet(enemy3_pos.x, enemy3_pos.y);
    }

  },
  createEnemyBullet: function (x, y) {
    let enemyBullet = null;
    enemyBullet = this.pools.getNode("enemyBulletPool", this.enemyBullet);
    enemyBullet.parent = this.node; // 将生成的敌人子弹加入节点树
    enemyBullet.setPosition(x, y);
  },
  creatBoss: function (params) {
    if (this.isCreatBoss == true) return;
    this.schedule(() => {
      let boolen = this.BossWarning.active;
      this.BossWarning.active = !boolen;
      this.hitWarning.active = !boolen;
    }, 0.4, 5)
    let enemyBoss = cc.instantiate(this.enemyBoss);
    enemyBoss.parent = this.node;
    enemyBoss.setPosition(0, this.viewHeight / 2 + 200);
    cc.tween(enemyBoss)
      .to(this.enemyBossMoveTime, { position: cc.v2(0, this.viewHeight / 2 - 200) }) //出场动画
      .to(2, { position: cc.v2(200, this.viewHeight / 2 - 200) })
      .to(4, { position: cc.v2(-200, this.viewHeight / 2 - 200) })
      .to(2, { position: cc.v2(0, this.viewHeight / 2 - 200) })
      .to(2, { position: cc.v2(0, this.viewHeight / 2 - 200) })
      .to(2, { position: cc.v2(300, 0) })
      .to(4, { position: cc.v2(-300, -100) })
      .to(3, { position: cc.v2(0, this.viewHeight / 2 - 200) })
      .start();
    this.isCreatBoss = true;
  },
  onBullet_Killenemy(enemy, enemyType) {
    //将敌人对象回收到对象池
    if (enemyType == 1) {
      this.pools.putNode(PoolConfig.enemy1, enemy);
    } else if (enemyType == 2) {
      this.pools.putNode(PoolConfig.enemy2, enemy);
    } else if (enemyType == 3) {
      this.pools.putNode(PoolConfig.enemy3, enemy);
    }
  },
  checkNUmber: function () {
    if (!DataMangrt.level) return //跳过无尽模式
    DataMangrt.nowKillEnemyNum++;
    this.killEnemy_bar.getComponent(cc.ProgressBar).progress += 1 / DataMangrt.enemyNum;
    if (DataMangrt.nowKillEnemyNum >= DataMangrt.enemyNum) {//击杀足够敌人召唤boss
      this.creatBoss();
    }
  },
  gameWin: function (params) {

    console.log('游戏胜利');
    DataMangrt.NowMaxLevel = DataMangrt.getData();
    this.isWinBg.active = true;
    if (DataMangrt.level == DataMangrt.NowMaxLevel) {
      if (DataMangrt.level == 10) {
        DataMangrt.game_isWin = true;
        this.isOverBg.active = true;
        return
      }
      DataMangrt.NowMaxLevel++;
      DataMangrt.saveData();
    }
    progress = 1;
    DataMangrt.Game_isWin = true;

  },
  update(dt) {
    if (DataMangrt.Game_isWin) return;
    if (this.isStart) {
      this.Bg_Moving();
      this.creatEnemytime++;
      this.ft++;
      if (this.ft >= 12) {
        //发射子弹间隔
        this.shoot();
        this.ft = 0;
      }

      if (DataMangrt.level == 0) {
        //无尽模式
        var randonNumEnemy = 5; /**增加游戏难度 */ //自认为毛用没有
        this.gameTime++;
        if (this.gameTime % 300 == 0) {
          randonNumEnemy = randonNumEnemy + Math.round(this.gameTime / 300); //round四舍五入
          if (randonNumEnemy > 20) {
            randonNumEnemy = 20;
          }
          this.randomNum[0] = this.randomNum[0] - 2; //让敌机1 2出现概率逐渐增大
          this.randomNum[1] = this.randomNum[1] - 1;
          if (this.randomNum[0] < 40) {
            this.randomNum[0] = 40;
          }
          if (this.randomNum[1] < 75) {
            this.randomNum[1] = 75;
          } //这样的话敌机3的概率就变为了25%
        }
        if (this.creatEnemytime >= 120) {
          //生成无尽敌人时间间隔
          this.creatEnemytime = 0;
          let num_random = Math.floor(Math.random() * 5) + 1; //控制每次生成敌人数量
          for (let i = 0; i < num_random; i++) {
            let num = Math.random() * 100;
            if (num < this.randomNum[0]) {
              this.Creat_Enemy(1);
            } else if (num < this.randomNum[1]) {
              this.Creat_Enemy(2);
            } else if (num < this.randomNum[2]) {
              this.Creat_Enemy(3);
            }
          }
        }
      } else {
        //关卡模式
        if (this.creatEnemytime >= 50) {
          //生成关卡敌人时间间隔
          this.creatEnemytime = 0;

          if (0 < DataMangrt.level && DataMangrt.level <= 3) {
            let num_random = Math.floor(Math.random() * DataMangrt.level * 2); //控制每次生成敌人数量
            for (let i = 0; i < num_random; i++) {
              this.Creat_Enemy(1);
            }
          } else if (DataMangrt.level <= 6) {
            let num_random = Math.floor(Math.random() * DataMangrt.level);
            for (let i = 0; i < num_random; i++) {
              this.Creat_Enemy(1);
              this.Creat_Enemy(2);
            }
          } else {
            let num_random = Math.floor((Math.random() * DataMangrt.level) / 2);
            for (let i = 0; i < num_random; i++) {
              this.Creat_Enemy(1);
              this.Creat_Enemy(2);
              this.Creat_Enemy(3);
            }
          }
        }
      }
    }
  },
});
